# -*- coding: utf-8 -*-
###############################################################################
# file    : views_auth.py
# author  : wangyubin
# date    : Tue Apr  8 16:58:37 2014
#
# brief   : views for 云平台的用户
# history : init
###############################################################################

# uliweb lib
from uliweb import expose, functions
# python lib
import os
import datetime
# CM-box lib
from db_app.model_define import *
from comm_app.my_log import App_Log
from comm_app import utils

@expose('/auth')
class views_auth(object):
    """ 站点的用户和权限处理
    """

    def __init__(self):
        pass

    @expose('register')
    def register(self):
        """
        """

        if request.method == 'GET':
            return {
                'result' : 0,
                'message': '',
            }

        App_Log.logger.debug(request.POST)
        name=request.POST.get("txt-username")
        real_name=request.POST.get("txt-realname")
        passwd=request.POST.get("txt-passwd")
        email=request.POST.get("txt-email")
        telephone=request.POST.get("txt-telephone")

        user_count = T_USER.filter(T_USER.c.name == name).count()

        if user_count > 0:
            return {
                'result':-1,
                'message':settings.MESSAGE.AUTH_MSG_02,
            }

        user=T_USER()
        user.name=name
        user.real_name = real_name
        user.passwd=passwd
        user.email=email
        user.telephone=telephone
        user.save()

        return redirect("/login")


    @expose('/login')
    def login(self):
        """ 登录
        """

        if request.method == 'GET':
            return {
                'result' : 0,
                'message': '',
            }

        # POST中获取用户名和密码
        App_Log.logger.debug(request.POST)
        username = request.POST.get("txt-username")
        passwd   = request.POST.get("txt-passwd")
        remember = False
        if request.POST.get('remember'):
            remember = True
        # 和数据库中的用户名和密码比对
        user = T_USER.filter(T_USER.c.name == username) \
                     .filter(T_USER.c.passwd == passwd).one()
        # 用户名和密码正确 -> 1. 创建session, session中保存用户名, 用户id etc...
        #                     2. 迁移到 系统状态页面 state_app/index
        # 用户名和密码错误 -> 在login页面显示错误信息
        if user:                # 用户名和密码正确
            App_Log.logger.debug("登录成功")
            dic                                          = {}
            dic["userid"]                                = user.id
            request.session[settings.SESSION.SESSION_ID] = dic
            request.session.remember                     = remember

            return Redirect('/')
        else:
            App_Log.logger.warn("登录失败!")
            return {
                "result" : -1,
                "message": settings.MESSAGE.AUTH_MSG_01,
            }


    @expose('logout')
    def logout(self):
        """ 注销
        """
        request.session.delete()
        return redirect('/login')


    @expose("profile")
    def profile(self):
        """ 迁移到修改profile的页面
        """
        user = request.user

        return {
            "realname": user.real_name,
            "email": user.email,
            "telephone": user.telephone,
        }

    @expose("change-passwd")
    def change_passwd(self):
        """ 修改密码
        """

        old_passwd = request.POST.get("old-passwd")
        new_passwd = request.POST.get("new-passwd")

        user = request.user
        if user.passwd == old_passwd:
            user.update(passwd=new_passwd)
            user.save()
            result="OK"
            message=settings.MESSAGE.AUTH_MSG_04
        else:
            result="NG"
            message=settings.MESSAGE.AUTH_MSG_03

        return json({
            "result":result,
            "message":message,
        })


    @expose("change-profile")
    def change_profile(self):
        """ 修改 用户信息
        """

        userid = request.session[settings.SESSION.SESSION_ID]["userid"]
        new_realname =request.POST.get("new-realname")
        new_email=request.POST.get("new-email")
        new_telephone=request.POST.get("new-telephone")

        App_Log.logger.debug(u'new_realname: ' + new_realname)
        App_Log.logger.debug(u'new_email: ' + new_email)
        App_Log.logger.debug(u'new_telephone: ' + new_telephone)
        
        user = request.user
        user.update(real_name=new_realname, email=new_email, telephone=new_telephone)
        user.save()
        
        return json({
            "result":"OK",
            "message":settings.MESSAGE.AUTH_MSG_05,
        })

